<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header @addTodo="addTodo" />
      <List :todos="todos" @updateTodoIsDone="updateTodoIsDone"/>
      <Footer />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getTodosApi, addTodoApi, updateTodoIsDoneApi } from "./api/todo";
import type { TodoList } from "./api/types";

import Header from "./views/header/index.vue";
import List from "./views/list/index.vue";
import Footer from "./views/footer/index.vue";

// 数据源在哪，更新数据方法就应该定义在哪
// 其他组件要使用，将更新数据方法传递给它使用
const todos = ref<TodoList>([]);

// 获取todoList
const getTodos = async () => {
  const res = await getTodosApi();
  todos.value = res.data.data;
};

onMounted(getTodos);

// 添加todo
const addTodo = async (name: string) => {
  await addTodoApi(name); // 添加todo
  await getTodos(); // 获取todoList
};

// 更新todo
const updateTodoIsDone = async (id: number) => {
  await updateTodoIsDoneApi(id);
  await getTodos(); // 获取todoList
}
</script>

<style scoped>
/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
